// 创建表

const { standTables } = require("../../../../../app/tables-data");
const { N, needParam } = require("../../utils");
const { getIsSqlVar } = require("./_utils");

/**
 * 生成创建table的sql语句
 * @param {object[]} fields 要生成的字段
 * @returns
 */
const sqlKeywords = ["desc", "order", "group"]; // sql语句中的关键字
function getCreateTableSql(fields = []) {
  const strs = fields.map(item => {
    const { name, type, length, decimal, notNull, isPrimaryKey, remark, defaultValue, isAutoIncrement, isUnsigned, isFillZero } = item;
    if (sqlKeywords.includes(name)) throw new Error(`字段名不能用关键字：${name}`);
    const originDataType = type.toUpperCase();
    let dataType = originDataType;
    if (length !== undefined) {
      // TINYTEXT TEXT MEDIUMTEXT LONGTEXT TINYBLOB BLOB MEDIUMBLOB LONGBLOB
      if (!(dataType.endsWith("TEXT") || dataType.endsWith("BLOB"))) {
        dataType += `(${length})`;
      }
    }
    let decimalStr = "";
    if (decimal !== undefined) {
      if (length === undefined) throw new Error(`存在小数点位数时，必须传入长度：${name}`);
      decimalStr = `DECIMAL(${length}, ${decimal})`;
      dataType = ""; // Float 不能和 Decimal 同时出现
    }
    const unsignedStr = isUnsigned ? "UNSIGNED" : "";
    const notNullStr = notNull ? "NOT NULL" : "";
    const primaryKey = isPrimaryKey ? "PRIMARY KEY" : "";
    const remarkStr = remark ? `COMMENT '${remark}'` : "";
    let defValStr = "";
    if (defaultValue !== undefined) {
      const isNum = originDataType.includes("INT") || ["FLOAT", "DOUBLE"].includes(originDataType);
      if (getIsSqlVar(defaultValue) || isNum) {
        defValStr = `DEFAULT ${defaultValue}`;
      } else {
        defValStr = `DEFAULT '${defaultValue}'`;
      }
    } else {
      if (name === "update_time") {
        defValStr = `DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP`;
      }
      // else {
      //   const isStr = true; // 变长字符串等、文本等
      //   if(isStr){
      //     defValStr = `DEFAULT ''`;
      //   }
      // }
    }
    const autoIncrementStr = isAutoIncrement ? "AUTO_INCREMENT" : "";
    const fillZeroStr = isFillZero ? "ZEROFILL" : "";
    const str = `${name} ${dataType} ${decimalStr} ${unsignedStr} ${notNullStr} ${primaryKey} ${defValStr} ${autoIncrementStr} ${fillZeroStr} ${remarkStr}`;
    return str.replace(/ {2,}/g, " ").trim();
  });
  return strs.join(`,${N}`);
}

/**
 * 创建表
 * @param {string} name 表名称
 * @param {boolean} isOver 是否覆盖，若为true，则先删除表，然后重新创建表
 */
// 使用示例：
exports.createTable = function (tableName = needParam(), isOver = false) {
  if (!standTables[tableName]) throw new Error(`未找到表：${tableName}`);
  const { name, sqlFields } = standTables[tableName];
  const createSql = getCreateTableSql(sqlFields);
  if (sqlKeywords.includes(tableName)) throw new Error(`字段名不能用关键字：${tableName}`);
  let sql = `CREATE TABLE IF NOT EXISTS ${tableName} (${N}${createSql}${N});`;
  if (isOver) {
    sql = `DROP TABLE IF EXISTS ${tableName};
CREATE TABLE ${tableName} (${N}${createSql}${N}) `;
  }
  // unicode - 基于 Unicode 的排序规则
  // ci - Case Insensitive (大小写不敏感)：忽略字母大小写差异（'A' = 'a'）、搜索和比较时不区分大小写
  sql += `ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='${name}表';`;
  return sql;
};

// 删除表
// 复制表
